import json
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.edge.options import Options
import requests
from bs4 import BeautifulSoup
import random
import time


def getBaiduSeachList(list):
    url = 'http://top.baidu.com/buzz?b=1&fr=topindex'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'

    }
    r = requests.get(url, headers=headers, timeout=30)
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text, 'html.parser')
    title_list = soup.find_all(attrs={'class': 'c-single-text-ellipsis'})
    for data in title_list:
        list.append(str(data.get_text()).strip())


def getPoemSearchList(list):
    file_url = "https://gitee.com/windy278/search-word/raw/master/poem.txt"
    try:
        response = requests.get(file_url)
        response.raise_for_status()
        # 按行切割文本内容
        lines = response.text.splitlines()  # 或 response.text.split('\n')
        for line in lines:
            list.append(line)
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")


def OpenUrl(url):
    driver.get('https://cn.bing.com/')
    time.sleep(2)
    search_box = driver.find_element("name", "q")
    search_box.send_keys(url)
    search_box.send_keys(Keys.RETURN)
    with open('cookies.txt', 'r') as f:
        cookies_list = json.load(f)
        for cookie in cookies_list:
            if isinstance(cookie.get('expiry'), float):
                cookie['expiry'] = int(cookie['expiry'])
            driver.add_cookie(cookie)
    time.sleep(2)


def run_search(search_str):
    # OpenUrl('http://cn.bing.com/search?q=' + str(search_str))
    OpenUrl(str(search_str))


def getScore(str_head, data_list, times):
    for i in range(times):
        run_search(data_list[0])
        print(str_head + '第', i + 1, '次完成')
        data_list.remove(data_list[0])
        sleep_time = random.randint(10, 15)  # 随机等待10到15秒
        print('等待', sleep_time, '秒')
        time.sleep(sleep_time)

    driver.quit()


if __name__ == "__main__":
    timesPC = 30  # 电脑搜索次数
    timesMobile = 20  # 移动设备搜索次数
    List = []
    getBaiduSeachList(List)
    getPoemSearchList(List)
    random.shuffle(List)

    options = Options()

    # 电脑搜索
    driver = webdriver.Edge()
    getScore('电脑搜索', List, timesPC)
    print('电脑搜索完成')

    # # 移动设备搜索
    # with open('deviceName.txt') as f:
    #     deviceName = f.readline()
    # mobile_emulation = {'deviceName': deviceName}  # 添加移动设备搜索
    # options.add_experimental_option("mobileEmulation", mobile_emulation)  # 使用移动设备搜索模拟器打开
    # driver = webdriver.Edge(options=options)
    # # # 如果手机端更换设备也一直不成功，请注释掉上面三行并启用下面三行
    # # options_edge = Options()
    # # options_edge.add_argument("--auto-open-devtools-for-tabs")  # 打开F12
    # # driver = webdriver.Edge(options=options_edge)  # F12不能无窗口运行
    # getScore('移动设备搜索', List, timesMobile)
    # print('移动设备搜索完成')
